// eventBus.ts

export interface EventMap {
  'user:login': { userId: string; name: string };
  'notification:show': { message: string; type: 'success' | 'error' };
  'data:loaded': void;

  // +++ 添加 EventBusDemoPage 中使用的事件及其数据类型 +++
  'app:userLogin': { id: number; name: string; email: string; }; // 对应 USER_LOGIN
  'app:userLogout': void; // 对应 USER_LOGOUT
  'app:themeChange': { theme: 'light' | 'dark'; }; // 对应 THEME_CHANGE
  'app:notificationAdd': { message: string; timestamp: number; }; // 对应 NOTIFICATION_ADD
  // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  [key: string]: any; // 允许其他未定义的事件，灵活性高但类型不安全
}

export type EventCallback<T = any> = (data: T) => void;

interface EventBus<E extends Record<string, any>> {
  on<K extends keyof E>(key: K, callback: EventCallback<E[K]>): () => void;
  once<K extends keyof E>(key: K, callback: EventCallback<E[K]>): () => void;
  off<K extends keyof E>(key: K, callback: EventCallback<E[K]>): void;
  trigger<K extends keyof E>(key: K, data?: E[K]): void;
  clear(key: keyof E): void;
  clearAll(): void;
}

export class EventBusImpl<Events extends Record<string, any>> implements EventBus<Events> {
  private events: Map<keyof Events, Set<EventCallback<any>>> = new Map();

  on<K extends keyof Events>(key: K, callback: EventCallback<Events[K]>): () => void {
    let callbacks = this.events.get(key);
    if (!callbacks) {
      callbacks = new Set();
      this.events.set(key, callbacks);
    }
    callbacks.add(callback);
    return () => {
      this.off(key, callback);
    };
  }

  once<K extends keyof Events>(key: K, callback: EventCallback<Events[K]>): () => void {
    const wrapper = (data: Events[K]) => {
      this.off(key, wrapper as EventCallback<Events[K]>);
      callback(data);
    };
    return this.on(key, wrapper as EventCallback<Events[K]>);
  }

  off<K extends keyof Events>(key: K, callback: EventCallback<Events[K]>): void {
    const callbacks = this.events.get(key);
    if (callbacks) {
      callbacks.delete(callback);
      if (callbacks.size === 0) {
        this.events.delete(key);
      }
    }
  }

  trigger<K extends keyof Events>(key: K, data?: Events[K]): void {
    const callbacks = this.events.get(key);
    if (callbacks) {
      for (const callback of callbacks) {
        try {
          callback(data);
        } catch (error) {
          console.error(
              `EventBus: 事件 "${String(key)}" 的回调函数执行出错。`,
              { error, callbackData: data }
          );
        }
      }
    }
  }

  clear(key: keyof Events): void {
    this.events.delete(key);
  }

  clearAll(): void {
    this.events.clear();
  }
}

export const eventBus = new EventBusImpl<EventMap>(); // 确保这里使用了 EventMap